import os

from pathlib import Path
from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import Field

ROOT_DIR = Path(__file__).resolve().parent.parent.parent  # E:\stu_ai\

class Settings(BaseSettings):
    """
    项目配置类（Python 3.12优化版）

    从环境变量、.env文件和pyproject.toml读取配置
    """
    # 项目基本信息
    project_name: str = "智能题库与考试系统"
    api_v1_str: str = "/api/v1"

    # 数据库配置
    mysql_server: str = Field(alias="MYSQL_SERVER")
    mysql_port: int = Field(alias="MYSQL_PORT")
    mysql_user: str = Field(alias="MYSQL_USER")
    mysql_password: str = Field(alias="MYSQL_PASSWORD")
    mysql_db: str = Field(alias="MYSQL_DB")

    # # Dify配置
    # dify_api_key: str = Field(alias="DIFY_API_KEY")
    # dify_base_url: str = Field(alias="DIFY_BASE_URL")
    # dify_model_id: str = Field(alias="DIFY_MODEL_ID")

    # 日志配置
    log_level: str = Field("INFO", alias="LOG_LEVEL")

    # 配置模型（Pydantic v2）
    model_config = SettingsConfigDict(
        env_file=os.path.join(ROOT_DIR, ".env"),  # 指定 .env 路径
        env_file_encoding="utf-8",  # 编码格式
        case_sensitive=False,  # 不区分大小写
        extra="ignore"  # 忽略未定义的字段
    )

    @property
    def db_url_sync(self) -> str:
        """构建数据库连接URL"""
        return (f"mysql+pymysql://{self.mysql_user}:{self.mysql_password}@"
                f"{self.mysql_server}:{self.mysql_port}/"
                f"{self.mysql_db}?charset=utf8mb4")

    @property
    def db_url_async(self) -> str:
        """异步MySQL连接URL（用于FastAPI主程序）"""
        return (f"mysql+aiomysql://{self.mysql_user}:{self.mysql_password}@"
                f"{self.mysql_server}:{self.mysql_port}/"
                f"{self.mysql_db}?charset=utf8mb4")


# 创建配置实例
settings = Settings()

if __name__ == "__main__":
    print(settings.db_url_sync)